﻿@using TextAdventures.Quest;
@using WebEditor.Views.Edit;
@model WebEditor.Models.Element
           
<script type="text/javascript">
    function initializeAttributeListEditor(){
        $('#attributeRowEditor').hide();
        $('.attributeRow').hover(function () {
            $(this).css('background-color', '#DFEFFC');
        }, function () {
            var cssObj = {
                'background-color': 'white'
            };
            $(this).not('.selected').css(cssObj);
        });

        $('.attributeRow').click(function () {
            var cssObj = {
                'background-color': '#DFEFFC'
            };
            $(this).addClass('selected').css(cssObj);
            $(this).siblings().removeClass('selected').css('background-color', 'white');

            var key = $(this).children('.attributeName').first().html();
            $.get('/Edit/EditAttribute?id=@(Model.GameId)&key=@(Model.Key)&attributeName=' + key, function (result) {
                $('#attributeRowEditor').html(result).show('slow');
                initialiseElementEditorControls($("#attributeRowEditor"));
            });
        });
    }

    $(document).ready(function () {
        initializeAttributeListEditor();
    });
</script>
           
<div id="form-loading">
Working...
</div>

@if (!string.IsNullOrEmpty(Model.Error))
{
    <div class="elementEditorError">
        <b>Sorry, an internal error occurred:</b><br />
        @Model.Error
    </div>
}

@if (Model.OtherElementErrors != null && Model.OtherElementErrors.Count > 0)
{
    <div class="elementEditorError">
        @foreach (var data in Model.OtherElementErrors)
        {
            <text>"@data.Key" has the following errors:</text>
            <ul>
                @foreach (string message in data.Value)
                {
                    <li>@message</li>
                }
            </ul>
        }
    </div>
}

<div id="elementEditorForm">
    @if (!string.IsNullOrEmpty(Model.Name))
    {
    <div class="elementEditorHeader">
        <div class="elementEditorButtons">
            @if (Model.CanMove && !string.IsNullOrEmpty(Model.MovePossibleParents))
            {
            <button type="button" id="button-move">Move</button>
            }
            @if (Model.IsElement && Model.Name != "game")
            {
            <button type="button" id="button-delete">Delete</button>
            }
            @if (Model.Name == "game")
            {
                <button type="button" id="button-publish">Publish</button>
            }
        </div>

        <div class="elementEditorName">@Model.Name</div>
    </div>
    }

    @using (Ajax.BeginForm("SaveElement", new { }, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "elementEditorForm", OnSuccess = "initialiseElementEditor", OnFailure = "ajaxError", OnBegin = "beginFormSubmit" }))
    {
        <div id="hiddenElementValues">
            <input type="hidden" name="_game_id" id="_game_id" value="@Model.GameId" />
            <input type="hidden" name="_key" id="_key" value="@Model.Key" />
            <input type="hidden" name="_redirectToElement" id="_redirectToElement" value="@Model.Key" />
            <input type="hidden" name="_additionalAction" id="_additionalAction" value="" />
            <input type="hidden" name="_additionalActionTab" id="_additionalActionTab" value="@Model.Tab" />
            <input type="hidden" name="_ignoreExpression" id="_ignoreExpression" value="" />
            <input type="hidden" name="_refreshTreeSelectElement" id="_refreshTreeSelectElement" value="@Model.RefreshTreeSelectElement" />
            <input type="hidden" name="_popupError" id="_popupError" value="@Model.PopupError" />
            <input type="hidden" name="_newObjectPossibleParents" id="_newObjectPossibleParents" value="@Model.NewObjectPossibleParents" />
            <input type="hidden" name="_enabledButtons" id="_enabledButtons" value="@Model.EnabledButtons" />
            <input type="hidden" name="_pageTitle" id="_pageTitle" value="@Model.PageTitle" />
            <input type="hidden" name="_reload" id="_reload" value="@Model.Reload" />
            <input type="hidden" name="_availableVerbs" id="_availableVerbs" value="@Model.AvailableVerbs" />
            <input type="hidden" name="_uiAction" id="_uiAction" value="@Model.UIAction" />
            <input type="hidden" name="_movePossibleParents" id="_movePossibleParents" value="@Model.MovePossibleParents" />
            <input type="hidden" name="_allObjects" id="_allObjects" value="@Model.AllObjects" />
            <input type="hidden" name="_hiddenScripts" id="_hiddenScripts" value="@Model.HiddenScripts" />
            <input type="hidden" name="_scriptCategories" id="_scriptCategories" value="@Model.ScriptCategories" />
        </div>
        if (Model.NextPage != null)
        {
            <input type="hidden" name="_nextPage" id="_nextPage" value="@Model.NextPage" />
        }
        if (Model.EditorDefinition != null)
        {
            <div id="elementEditorTabs">
                @{
                    int count = 0;
                }
                <ul>    
                    @foreach (IEditorTab def in Model.EditorDefinition.Tabs.Values)
                    {
                        if (!def.IsTabVisible(Model.EditorData) || def.GetBool("desktop"))
                        {
                            continue;
                        }
                        if (Model.Controller.SimpleMode && !def.IsTabVisibleInSimpleMode)
                        {
                            continue;
                        }
                        count++;
                        string id = "#elementEditorTab" + count;
                        if (def.Caption == "Attributes")
                        {
                            <li class="saveBeforeLoad"><a href="@id">@def.Caption</a></li>
                        }
                        else
                        {
                            <li><a href="@id">@def.Caption</a></li>
                        }
                    }
                </ul>
                @{
                    count = 0;
                }
                @foreach (IEditorTab def in Model.EditorDefinition.Tabs.Values)
                {
                    if (!def.IsTabVisible(Model.EditorData) || def.GetBool("desktop"))
                    {
                        continue;
                    }
                    if (Model.Controller.SimpleMode && !def.IsTabVisibleInSimpleMode)
                    {
                        continue;
                    }
                    count++;
                    string id = "elementEditorTab" + count;
                    <div id="@id">
                        @{
                           bool isFirst = true;
                        }
                        <table style="width: 100%">
                            <colgroup>
                                <col style="width: 15%" />
                                <col />
                            </colgroup>
                            @foreach (IEditorControl ctl in def.Controls)
                            {
                                if (!ctl.IsControlVisible(Model.EditorData) || ctl.GetBool("desktop"))
                                {
                                    continue;
                                }
                                if (Model.Controller.SimpleMode && !ctl.IsControlVisibleInSimpleMode)
                                {
                                    continue;
                                }
                                if (ctl.Attribute != null && Html.ViewData.ModelState.ContainsKey(ctl.Attribute))
                                {
                                    <tr>
                                        <td class="elementEditorCell" colspan="2">
                                            <div class="elementEditorError">
                                                @Html.ValidationMessage(ctl.Attribute)
                                                <button type="button" class="error-clear" data-key="@ctl.Attribute">Clear</button>
                                            </div>
                                        </td>
                                    </tr>
                                }

                                if (IsSelfCaption(ctl))
                                {
                                    <tr>
                                        <td class="elementEditorCell" colspan="2">@RenderEditorControl(ctl, isFirst, ctl.ControlType)</td>
                                    </tr>
                                }
                                else if (IsLongCaption(ctl))
                                {
                                    <tr>
                                        <td colspan="2">@ctl.Caption:</td>
                                    </tr>
                                    <tr>
                                        <td class="elementEditorCell" colspan="2">@RenderEditorControl(ctl, isFirst, ctl.ControlType)</td>
                                    </tr>
                                }
                                else
                                {
                                    <tr>
                                        <td class="elementEditorCaption">@ctl.Caption:</td>
                                        <td class="elementEditorCell">
                                            @RenderEditorControl(ctl, isFirst, ctl.ControlType)
                                        </td>
                                    </tr>
                                }
                                isFirst = false;
                            }
                        </table>
                    </div>
                }
            </div>
            <input id="elementEditorSave" type="submit" value="Save" style="display: none" />
        }
    }
</div>

@helper RenderEditorControl(IEditorControl ctl, bool isFirst, string controlType, string caption = null)
{
    var model = new WebEditor.Models.Controls.EditorControl
    {
        GameId = Model.GameId,
        Key = Model.Key,
        Controller = Model.Controller,
        EditorData = Model.EditorData,
        Control = ctl,
        IsFirst = isFirst,
        ControlType = controlType,
        Caption = caption
    };
    Html.RenderPartial("Controls/EditorControl", model);
}

@functions {
    bool IsLongCaption(IEditorControl ctl)
    {
        if (ctl.Caption == null) return false;
        return (ctl.Caption.Length > 15);
    }

    bool IsSelfCaption(IEditorControl ctl)
    {
        switch (ctl.ControlType)
        {
            case "checkbox":
            case "label":
            case "title":
                return true;
            case "multi":
                return ctl.GetString("selfcaption") != null;
        }
        if (string.IsNullOrEmpty(ctl.Caption)) return true;
        return false;
    }
}